// pages/order/order.js
var app = getApp()
var modal = require('../../utils/modal');
var request = require('../../utils/request');
var utils = require('../../utils/utils');
var storage = require('../../utils/storage');
var pay = require('../../common/wxpay');

var pageSetting = {
    callback:function(componentName){
        var that = this;
        switch(componentName){
            case 'commentContent':
                var data = {
                    'dp:api:act:ordercomment':{
                        'order_id':that['data']['listData']['order_id'],
                        'act_id':that['data']['listData']['act_id'],
                        'content':arguments[1]
                    }
                }
                console.log(data)
                // commentFun(data);
                break;
            default:
                break;
        }
    },
    data: {
        page:1,
        pageFlag:true,
        refundHidden:true,
        modalHidden: true,
        reminderHidden: true,
        listData:[],
        flag:1,
        orderId:null,
        index:null,
        aTime:{},
        isShowMask : false,
        maskData : {},
        reasonIdx : null,
        reasonArr : [
            '不想要了/下错单',
            '操作有误（地址、商品写错）',
            '货品质量问题／过了生产日期',
            '快递一直未到，不能按时送达',
            '未按照约定时间发货', 
            '货送错了／量送少了',
            '其他原因'
        ]
    },
    onLoad:function(){
        app.globalData.listOrderState = false;
        modal.loading();
        var that = this;

        var data={
            'self:oc:order:batch':{
                "page":1,
                "page_size":10
            }
        }
        request.post({
            path: '/wxapp_api/api'
        },data)
            .then(function(res){
                var retData = res['self:oc:order:batch'];
                if(retData.ret != 0){
                  // modal.toast(retData.msg);
                  wx.navigateTo({
                    url: "../error/error"
                  })
                  return false;
                } 

                var listData = retData['data'];
                if(listData.length < 10){
                    that.setData({
                        flag:0
                    });
                }
                for(var i =0;i<listData.length;i++){
                    if(listData[i].express_info){
                        var tempExpressInfo = listData[i].express_info.split(',');
                        if(tempExpressInfo.length > 1){
                            listData[i]['express_info'] = tempExpressInfo[0] + ',...';
                        }
                    }
                    var newThunbnail = listData[i]['thumbnail'].split(',')[0];
                    listData[i]['thumbnail'] = newThunbnail;
                    that.data.listData.push(listData[i]);
                }

                var data = that.data.listData;
                var tempTime = '';
                for(var i=0;i<data.length;i++){
                    var presellTime = data[i].presell_time.split(' ')[0].split('-');
                    presellTime[1] = presellTime[1] < 10 ? parseInt(presellTime[1]) : presellTime[1];
                    presellTime[2] = presellTime[2] < 10 ? parseInt(presellTime[2]) : presellTime[2];
                    tempTime = presellTime[0] + '年' + presellTime[1] + '月' + presellTime[2] + '号';
                    data[i].temp_time = tempTime;
                }
                that.setData({
                    lists:data,
                });
                modal.hide();
            }); 
    },
    onShow : function(e){
        if(app.globalData.listOrderState){
            app.globalData.listOrderState = false;
            var that= this;
            var page = that.data.page;
            var pageFlag = that.data.pageFlag;
            if(that.data.flag == 0){
                return false;
            }
            modal.loading();
            if(that.data.pageFlag){
                pageFlag = false;
                that.setData({
                    page : page,
                    pageFlag : pageFlag
                });
                request.post({
                    path: '/wxapp_api/api'
                },{'self:oc:order:batch':{"page":page,"page_size":10}})
                    .then(function(res){
                        var retData = res['self:oc:order:batch'];
                        if(retData.ret != 0){
                          // modal.toast(retData.msg);
                          wx.navigateTo({
                            url: "../error/error"
                          })
                          return false;
                        } 

                        var listData = retData['data'];
                        if(listData.length < 10){
                            that.setData({
                                flag:0
                            });
                        }
                        var start = (page-1) * 10;
                        var end = start + listData.length;
                        for(var i=start;i<end;i++){
                            that.data.listData[i] = null;
                        }

                        for(var i =0;i<listData.length;i++){
                            if(listData[i].express_info){
                                var tempExpressInfo = listData[i].express_info.split(',');
                                if(tempExpressInfo.length > 1){
                                    listData[i]['express_info'] = tempExpressInfo[0] + ',...';
                                }
                            }
                            var newThunbnail = listData[i]['thumbnail'].split(',')[0];
                            listData[i]['thumbnail'] = newThunbnail;
                            that.data.listData[start] = listData[i];
                            start ++;
                        }

                        var data = that.data.listData;
                        var tempTime = '';
                        for(var i=0;i<data.length;i++){
                            var presellTime = data[i].presell_time.split(' ')[0].split('-');
                            if(presellTime){
                                presellTime[1] = presellTime[1] < 10 ? parseInt(presellTime[1]) : presellTime[1];
                                presellTime[2] = presellTime[2] < 10 ? parseInt(presellTime[2]) : presellTime[2];
                                tempTime = presellTime[0] + '年' + presellTime[1] + '月' + presellTime[2] + '号';
                                data[i].temp_time = tempTime;    
                            }else{
                                continue;
                            }
                        }

                        that.setData({
                            lists:data,
                            pageFlag : true,
                            page : page
                        });
                        modal.hide();
                    });
            }
        }
    },
    showPayMask : function(e){
        //申请退款
        var that = this;
        var data = e.target.dataset;
        var index = data.index;
        var orderId = data.id;
        var maskData = that.data.maskData;
        var listData = that.data.listData;
        maskData = listData[index];
        that.setData({
            maskData : maskData,
            index: index,
            isShowMask : true,
            i : ''
        });
    },
    hidePayMask : function(e){
        //取消申请退款
        var that = this;
        that.setData({
            isShowMask: false,
            reasonIdx: null
        });
    },
    bindPickerChange: function(e) {
        //申请退款原因
        var that = this;
        var reasonIdx = e.detail.value;
        that.setData({
            i : e.detail.value,
            reasonIdx : reasonIdx
        })
    },
    refundChange : function(e){
        //申请退款确定
        var that = this;
        var data = e.target.dataset;
        var reason = data.reason;
        var orderId = data.order_id;
        var oldStatus = data.status;
        var reasonIdx = that.data.reasonIdx;
        var listData = that.data.listData;
        var index = that.data.index;
        if(listData[index].order_source == 'zc'){
            var data = {
                'zp:zc_api:order:refund':{
                    'id':orderId,
                    'reason':reason
                    }
            }
        }else{
            var data = {
                'dp:api:act:refund':{
                    'id':orderId,
                    'reason':reason
                }
            }   
        }
        
        if(!reason && !reasonIdx){
            modal.toast('请选择退款原因','提示',function(){
            });
            return false;
        }else{
            request.post({
                path: '/wxapp_api/api'
            },data)
                .then(function(res){
                    if(listData[index].order_source == 'zc'){
                        var retData = res['zp:zc_api:order:refund'];
                    }else{
                       var retData = res['dp:api:act:refund'];   
                    }

                    var isShowMask = false;
                    if(retData.ret != 0){
                        that.setDate({
                            isShowMask : isShowMask
                        });
                        // modal.toast(retData.msg);
                        wx.navigateTo({
                            url: "../error/error"
                        })
                        return false;
                    }
                    if(listData[index].order_source == 'zc'){
                        if(retData.msg == 'ok'){
                            listData[index]['status_name'] = '申请退款中';
                            listData[index]['status'] = '12';
                            modal.toast('提交成功','提示',function(){
                            });
                        }
                    }else{
                        if(retData['data']['status']){
                            listData[index]['status_name'] = '申请退款中';
                            listData[index]['status'] = '12';
                            modal.toast('提交成功','提示',function(){
                            });
                        }  
                    }
                    that.setData({
                        isShowMask : isShowMask,
                        lists : listData,
                        reasonIdx : reasonIdx
                    })
                });
        }
    },
    reminderTap:function(e){
        //催单按钮
        this.setData({
            reminderHidden: false,
            orderId:e.target.dataset.id,
            index:e.target.dataset.index
        })
    },
    reminderCancel:function(){
        //催单取消按钮
        this.setData({
            reminderHidden: true
        })
    },
    reminderChange:function(e){
        //催单确定按钮  
        var that = this;
        var odata = e.target.dataset;
        var listData = that.data.listData;
        var index = that.data.index;
        var orderId = that.data.orderId;
        var reminderHidden = true;
        if(listData[index].order_source == 'zc'){
            var data = {
                'zp:zc_api:order:reminder':{
                    'id':orderId
                }
            }
        }else{
            var data = {
                'dp:api:act:reminder':{
                    'id':orderId
                }
            }   
        }
        request.post({
            path: '/wxapp_api/api'
        },data)
            .then(function(res){
                if(listData[index].order_source == 'zc'){
                    var retData = res['zp:zc_api:order:reminder'];
                }else{
                    var retData = res['dp:api:act:reminder'];
                }
                // if(res.ret != 0) {
                //     wx.navigateTo({
                //         url: "../error/error"
                //     })
                //     return false;
                // }
                if(listData[index].order_source == 'zc'){
                    if(retData.msg == 'ok'){
                        listData[index]['is_new_show_reminder'] = '2';
                        modal.toast('已去催单喽！','提示',function(){
                        });
                    }
                }else{
                    if(retData.ret != 0) {
                        modal.toast(retData.msg);
                        return false;
                    } else {
                        if(retData['data']['status']){
                            listData[index]['is_new_show_reminder'] = '2';
                            modal.toast('已去催单喽！','提示',function(){
                            });
                        }    
                    } 
                }
                that.setData({
                    reminderHidden : reminderHidden,
                    lists : listData
                }) 
            });
    },
    clickGoPay:function(e){
        var data = e.currentTarget.dataset;
        // wx.navigateTo({
        //   url: '../submit/submit?order_id=' + data.payid
        // })      
        pay.callwxPay(data.payid)
    },
    clickGoConfirm:function(e){  
        var that = this;    
        var odata = e.currentTarget.dataset;
        var listData = that.data.listData;
        var index = odata.index;
        if(listData[index].order_source == 'zc'){
            var data = {
                'zp:zc_api:order:receive':{
                    'id':odata.order_id
                }
            }
        }else{
            var data = {
                'dp:api:act:confirmGoods':{
                    'id':odata.order_id
                }
            }
        }
        
        request.post({
            path: '/wxapp_api/api'
        },data)
        .then(function(res){
            if(listData[index].order_source == 'zc'){
                var retData = res['zp:zc_api:order:receive'];
            }else{
                var retData = res['dp:api:act:confirmGoods'];
            }
            if(retData.ret != 0){
              // modal.toast(retData.msg);
              wx.navigateTo({
                url: "../error/error"
            })
              return false;
            }else{
                listData[index]['status_name']='已收货';
                modal.toast('操作成功','提示',function(){
                });
            }

            that.setData({
                lists:listData
            })  
        });
    },
    pullUpLoad:function(){
        var that= this;
        var page = that.data.page;
        var pageFlag = that.data.pageFlag;
        if(that.data.flag == 0){
            return false;
        }
        modal.loading();
        if(that.data.pageFlag){
            page ++;
            pageFlag = false;
            that.setData({
                page : page,
                pageFlag : pageFlag
            });
            request.post({
                path: '/wxapp_api/api'
            },{'self:oc:order:batch':{"page":page,"page_size":10}})
                .then(function(res){
                    var retData = res['self:oc:order:batch'];
                    if(retData.ret != 0){
                      // modal.toast(retData.msg);
                      wx.navigateTo({
                        url: "../error/error"
                      })
                      return false;
                    } 

                    var listData = retData['data'];
                    if(listData.length < 10){
                        that.setData({
                            flag:0
                        });
                    }

                    for(var i =0;i<listData.length;i++){
                        if(listData[i].express_info){
                            var tempExpressInfo = listData[i].express_info.split(',');
                            if(tempExpressInfo.length > 1){
                                listData[i]['express_info'] = tempExpressInfo[0] + ',...';
                            }
                        }
                        var newThunbnail = listData[i]['thumbnail'].split(',')[0];
                        listData[i]['thumbnail'] = newThunbnail;
                        that.data.listData.push(listData[i]);
                    }

                    var data = that.data.listData;
                    var tempTime = '';
                    for(var i=0;i<data.length;i++){
                        var presellTime = data[i].presell_time.split(' ')[0].split('-');
                        if(presellTime){
                            presellTime[1] = presellTime[1] < 10 ? parseInt(presellTime[1]) : presellTime[1];
                            presellTime[2] = presellTime[2] < 10 ? parseInt(presellTime[2]) : presellTime[2];
                            tempTime = presellTime[0] + '年' + presellTime[1] + '月' + presellTime[2] + '号';
                            data[i].temp_time = tempTime;    
                        }else{
                            continue;
                        }
                    }
                    that.setData({
                        lists:data,
                        pageFlag : true,
                        page : page
                    });
                    modal.hide();
                });
        }
    }
};
utils.assign(pageSetting);
Page(pageSetting);